from flask import Blueprint, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_jwt_extended import jwt_required
from flask_login import current_user
from extension import db
from config import Config
from views.user import admin_required, jwt_required
import os
from views.user import admin_required
from model import SubmissionResource

fm_bp = Blueprint('file_manage', __name__)


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in Config.ALLOWED_EXTENSIONS


@fm_bp.route('/preview_docu/<submissionR_id>', methods=['GET'])
def preview_docu(submissionR_id):
    #base_url = 'http://8.147.134.185/project/smart_plateform/uploads'
    #file_url = f'{base_url}/{filename}'
    report = SubmissionResource.query.filter_by(submissionR_id=submissionR_id).first()
    directory = os.path.dirname(report.file_path)
    filename = os.path.basename(report.file_path)

    return send_from_directory(directory, filename)


@fm_bp.route('/submit_docu', methods=['POST'])
@jwt_required()
def submit_report():
    file = request.files['file']
    data = request.form
    tid = data.get('tid')  #教师号
    cid = data.get('cid')  #课程号

    if not file or not tid or not cid:
        return jsonify({'error': 'Missing data'}), 400

    if not allowed_file(file.filename):
        return jsonify({'error': 'File not allowed'}), 400

    filename = file.filename
    file_path = os.path.join(Config.UPLOADED_FOLDER, filename)
    file.save(file_path)

    submission_resource = SubmissionResource(cid, tid, file_path)
    db.session.add(submission_resource)
    db.session.commit()

    return jsonify({'message': 'Report submitted successfully', 'file_path': file_path}), 201


@fm_bp.route('/check_docu', methods=['GET'])
@jwt_required()
def check_docu():
    # 假设你有一个方法来验证管理员身份4
    data = request.args
    tid = data.get('tid')
    cid = data.get('cid')
    print(tid, cid)

    if not tid or not cid:
        return jsonify({'error': 'Missing data'}), 400

    files = SubmissionResource.query.filter_by(course_id=cid, teacher_id=tid).all()
    file_list = [
        {'submissionR_id': file.submissionR_id, 'url': file.file_path,
         'submission_time': file.submission_time} for file in files]

    return jsonify(file_list), 200


@fm_bp.route('/download_docu/<int:submissionR_id>', methods=['GET'])
@jwt_required()
def download_docu(submissionR_id):
    submissionR_id = int(submissionR_id)
    report = SubmissionResource.query.filter_by(submissionR_id=submissionR_id).first()
    if not report:
        return jsonify({'error': 'Report not found'}), 404

    directory = os.path.dirname(report.file_path)
    filename = os.path.basename(report.file_path)

    return send_from_directory(directory, filename, as_attachment=True)


@fm_bp.route('/delete_docu/<int:submissionR_id>', methods=['POST'])
@jwt_required()
def delete_report(submissionR_id):
    submissionR_id = int(submissionR_id)
    report = SubmissionResource.query.filter_by(submissionR_id=submissionR_id).first()
    if not report:
        return jsonify({'error': 'Report not found'}), 404
        # 尝试删除文件

    try:
        os.remove(report.file_path)
    except Exception as e:
        return jsonify({'error': f'Failed to delete file: {str(e)}'}), 500

    db.session.delete(report)
    db.session.commit()
    return jsonify({'message': 'Report deleted successfully'}), 200
